package com.warmlight.voicepacket.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.google.gson.Gson;
import com.lzy.ninegrid.ImageInfo;
import com.lzy.ninegrid.NineGridView;
import com.lzy.ninegrid.preview.NineGridViewClickAdapter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.warmlight.voicepacket.CommentDetailAcitivity;
import com.warmlight.voicepacket.MainActivity;
import com.warmlight.voicepacket.R;
import com.warmlight.voicepacket.adapter.comm.CommDetailsAdapter;
import com.warmlight.voicepacket.bean.cdetails.CDetailsBean;
import com.warmlight.voicepacket.bean.cdetails.CDetailsInfoBean;
import com.warmlight.voicepacket.bean.cdetails.CDetailsListBean;
import com.warmlight.voicepacket.bean.comm.RecommPictureBean;
import com.warmlight.voicepacket.bean.comm.UserBean;
import com.warmlight.voicepacket.common.OttoConstants;
import com.warmlight.voicepacket.contract.VDetailsContract;
import com.warmlight.voicepacket.data.eventbus.MyCommunityLikeReply;
import com.warmlight.voicepacket.db.SharePreferenceUtil;
import com.warmlight.voicepacket.db.SharedPerfenceConstant;
import com.warmlight.voicepacket.http.HttpClient;
import com.warmlight.voicepacket.http.HttpConfig;
import com.warmlight.voicepacket.http.ResponseData;
import com.warmlight.voicepacket.loadmore.HeaderAndFooterRecyclerViewAdapter;
import com.warmlight.voicepacket.network.MapComm;
import com.warmlight.voicepacket.ottoEvent.OPictureBean;
import com.warmlight.voicepacket.ottoEvent.ORecommBean;
import com.warmlight.voicepacket.ottoEvent.OVideoBean;
import com.warmlight.voicepacket.ottoEvent.OttoBus;
import com.warmlight.voicepacket.plugin.QmzbMediaView;
import com.warmlight.voicepacket.plugin.QmzbVideoPlayer;
import com.warmlight.voicepacket.presenter.VDetailsPresenter;
import com.warmlight.voicepacket.ui.communitylm.widget.CommunityShare;
import com.warmlight.voicepacket.ui.communitylm.widget.ReplyBar;
import com.warmlight.voicepacket.ui.communitylm.widget.ReplyBarBase;
import com.warmlight.voicepacket.ui.user.LoginRegistActivity;
import com.warmlight.voicepacket.ui.user.usercenter.LookUserCenterActivity;
import com.warmlight.voicepacket.utils.JSONUtils;
import com.warmlight.voicepacket.utils.Log;
import com.warmlight.voicepacket.utils.SPUtils;
import com.warmlight.voicepacket.utils.ToastUtil;
import com.warmlight.voicepacket.utils.UIUtils;
import com.warmlight.voicepacket.view.AutoSwipeRefreshLayout;
import com.warmlight.voicepacket.view.LoadRecyclerView;

import org.greenrobot.eventbus.EventBus;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;

/**
 * Created by weiweijinpeng on 2018/9/12.
 */

public class VideoDetailsActivity extends com.warmlight.voicepacket.base.activity.BaseActivity implements View.OnClickListener,AutoSwipeRefreshLayout.OnRefreshListener,LoadRecyclerView.LoadListener,VDetailsContract.View,CommDetailsAdapter.VideoItemListener{

    private  String VIDEO_TYPE = "VIDEO_TYPE";
    public static final String VIDEO_HORIZONTAL = "VIDEO_HORIZONTAL";//横向视频
    public static final String VIDEO_VERTICAL = "VIDEO_VERTICAL";//竖向视频
    public static final String VIDEO_PICTURE = "VIDEO_PICTURE";//图文
    private float v;
//    private CDetailsListBean cDetailsListBean;
    private String itemId;
    private boolean isDEL;
    private Map<String, String> item;
    private SmartRefreshLayout smartRefreshLayout;
    private String isScroll;
    private LinearLayout ll_xm;
    private ImageView iv_more;


    public static void startVideoDetailsActivity(Context context,String itemId,String itemType,String isScroll,String tabType){
        Intent intent=new Intent(context,VideoDetailsActivity.class);
        intent.putExtra("itemId",itemId);
        intent.putExtra("tabType",tabType);
//        intent.putExtra("bean",(Serializable)cDetailsListBean);
        intent.putExtra("itemType",itemType);
        if (TextUtils.isEmpty(isScroll)){
            isScroll = "0";
        }
        intent.putExtra("isScroll",isScroll);//0 1
        context.startActivity(intent);
    }

    public static void startVideoDetailsActivity(Context context,String itemId,String itemType,Map<String,String> item,String comment_id,String reply_id){
        Intent intent=new Intent(context,VideoDetailsActivity.class);
        intent.putExtra("itemId",itemId);
//        intent.putExtra("bean",(Serializable)cDetailsListBean);
        intent.putExtra("msg", (Serializable) item);
        intent.putExtra("itemType",itemType);
        intent.putExtra("comment_id",comment_id);
        intent.putExtra("reply_id",reply_id);
        context.startActivity(intent);
    }



    List<CDetailsListBean> mData=new ArrayList<>();

    CDetailsInfoBean cDetailsInfoBean;

    VDetailsContract.Presenter mPresenter;

//    CommDetailsAdapter.FocusNormalViewHolder focusNormalViewHolder;

    @BindView(R.id.recycler_view)
    RecyclerView mRecyclerView;

    @BindView(R.id.cdetails_mediaview)
    QmzbMediaView qmzbMediaView;

    @BindView(R.id.seek_detail_background)
    SimpleDraweeView simpleDraweeView;

    @BindView(R.id.user_icon)
    SimpleDraweeView mUserIcon;

    @BindView(R.id.reply_bar_base_bottom)
    ReplyBarBase replyBarBaseBottom;

    @BindView(R.id.gridView_picarr)
    NineGridView playskinScrollGirdView;

    @BindView(R.id.scrollView)
    NestedScrollView scrollView;

    @BindView(R.id.header)
    RelativeLayout mHeaderLayout;

    @BindView(R.id.showdraw)
    ImageView mShowDraw;

    @BindView(R.id.recomm_nickname)
    TextView mNickName;

    @BindView(R.id.recomm_content)
    TextView mContentView;

    @BindView(R.id.recomm_details_like)
    TextView mCommLikeCount;

    @BindView(R.id.recomm_details_comments)
    TextView mCommentsCount;

    @BindView(R.id.recomm_details_share)
    TextView mShareCount;

    @BindView(R.id.view)
    View mView;

    @BindView(R.id.reply_bar)
    ReplyBar replyBar;

    @BindView(R.id.ll_tabbar)
    LinearLayout ll_tabbar;

    @BindView(R.id.ll_back)
    LinearLayout ll_back;

    @BindView(R.id.include_head)
    LinearLayout include_head;

    LinearLayoutManager linearLayoutManager;

    CommDetailsAdapter commDetailsAdapter;

    PlayHandler playHandler;

    private boolean isFocusChanged = false;

    int page;

    private int isLike;

    private int isLikeList;

    int likePosition;

    int videoHeight;

    private int isLikeType;//0是header点赞，1是列表点赞

    String topicContent;


    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video_details);

        getStatusBarId();
        onImmersionStatusBar();
        getIntentData();
        initView();

        Bundle bundle = getIntent().getExtras();
        String comment_id = "";
        String reply_id = "";
        if (bundle != null){
            itemId = bundle.getString("itemId");
            if (bundle.containsKey("comment_id")){
                comment_id = bundle.getString("comment_id");
                reply_id = bundle.getString("reply_id");
            }

            if (bundle.containsKey("msg")){
                item = (Map<String, String>) bundle.getSerializable("msg");
            }

            if (bundle.containsKey("isScroll")){
                isScroll = bundle.getString("isScroll");
            }else{
                isScroll = "0";
            }

        }

        loadDetail(comment_id,reply_id);
    }

    private void loadDetail(String comment_id, String reply_id) {
        String POSTDEL = HttpConfig.POSTDEL;
        TreeMap<String, String> treeMap = new TreeMap<>();
        treeMap.put("post_id", itemId);//帖子id
        treeMap.put("comment_id",comment_id);
        treeMap.put("reply_id",reply_id);
        HttpClient.getInstance().postRxAndroidAES(POSTDEL, treeMap)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseData>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ResponseData responseData) {

                        if (TextUtils.equals("200", responseData.getCode())) {
                            final CDetailsBean postDetalData = new Gson().fromJson(responseData.getData(), CDetailsBean.class);
                            cDetailsInfoBean=postDetalData.getPost_info();

                            playMedia();

                            CDetailsBean.DelBean del = postDetalData.getDel();
                            isDEL = false;
                            if (del.isReply_del()){
                                ToastUtil.showShort(VideoDetailsActivity.this,"回复已被删除");
                                isDEL = true;
                            }else if (del.isComment_del()){
                                ToastUtil.showShort(VideoDetailsActivity.this,"评论已被删除");
                                isDEL = true;
                            }else{

                            }
                            initData(true);
//
                        } else {
                            ToastUtil.showShort(VideoDetailsActivity.this,responseData.getMsg());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        ToastUtil.showShort(VideoDetailsActivity.this,"数据请求失败");
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    @Override
    public int getStatusBarId() {
        return R.id.status_padding;
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (!isFocusChanged) {
            isFocusChanged = true;
            int width = simpleDraweeView.getWidth();
            videoHeight = simpleDraweeView.getHeight();

            ViewGroup.LayoutParams lp=qmzbMediaView.getLayoutParams();

            if (VIDEO_TYPE.equals(VIDEO_VERTICAL)){
                lp.width= width;
                lp.height= videoHeight;
            }else if (VIDEO_TYPE.equals(VIDEO_HORIZONTAL)){
                lp.width= width;
                lp.height= width * 9 / 16;
            }

            qmzbMediaView.setLayoutParams(lp);
        }
    }


//    @RequiresApi(api = Build.VERSION_CODES.M)
    private void initView(){


        smartRefreshLayout = findViewById(R.id.smartrefreshlayout);

        smartRefreshLayout.setEnableRefresh(false);

        smartRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                initData(false);
            }
        });

        ll_xm = findViewById(R.id.ll_xm);
        iv_more = findViewById(R.id.iv_more);
        iv_more.setOnClickListener(this);
        LinearLayout ll_header_right  = findViewById(R.id.ll_header_right);
        ll_header_right.setOnClickListener(this);



        playHandler=new PlayHandler();
//        mRecyclerView.setLoadListener(this);

        mRecyclerView.setNestedScrollingEnabled(false);
        commDetailsAdapter = new CommDetailsAdapter(this,this);
//        mRecyclerView.setIsHaveData(false);

        linearLayoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(linearLayoutManager);
        //自定义加载布局
        HeaderAndFooterRecyclerViewAdapter customAdapter = new HeaderAndFooterRecyclerViewAdapter(commDetailsAdapter);
        mRecyclerView.setAdapter(customAdapter);
        //底部view
        bottomVisibility();

        initReplyBar();
    }

    /**
     * 设置回复框的参数
     * @param cDetailsInfoBean
     */
    private void setReplyBar(CDetailsInfoBean cDetailsInfoBean){
        String id = cDetailsInfoBean.getId();
        if (replyBar != null){
            replyBar.setReplyBar(0,id,"0",cDetailsInfoBean.getUser().getUid());
        }
    }

    private void initReplyBar(){
//        final ReplyBarBase replyBarBase = findViewById(R.id.reply_bar_base);
        replyBar = findViewById(R.id.reply_bar);
        replyBar.setReplyBarHint("说点什么吧，期待你的神评论");
        replyBarBaseBottom.setOnReplyBarBaseClickListener(new ReplyBarBase.ReplyBarBaseClickListener() {
            @Override
            public void clickText() {
                replyBar.showReplyBar(true,true);
            }

            @Override
            public void clickImg() {
                replyBar.showReplyBar(true,false);
                replyBar.addPhoto();
            }
        });
        scrollView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                replyBar.setOnTouch();
                return false;
            }
        });


        replyBar.setOnReplyBarLisener(new ReplyBar.ReplyBarReplySuccessLisener() {
            @Override
            public void success(CDetailsListBean data) {

                commDetailsAdapter.addItem(data);
                String comment_num = cDetailsInfoBean.getComment_num();
                if (!comment_num.contains("w") && !comment_num.contains("k")) {

                    Long num = Long.valueOf(comment_num) + 1;
                    cDetailsInfoBean.setComment_num(num + "");
                    String n = num+"";
//                    String priaiseComm = FormUnitUtils.form(BigDecimal.valueOf(num), "w");
                    if (TextUtils.equals("0", n)) {
                        n = "评论";
                    }
                    mCommentsCount.setText(n);

                    //这里用来区分是哪一个tab点击的，来进行不同的观察者接受事件
                    String tabType=getIntent().getStringExtra("tabType");

                    mSharePreferenceUtil.setString(SharedPerfenceConstant.DEATILSCOMMCLICK,n);

                    if (tabType.equals("recomm")){
                        OttoBus.getInstance().post(new ORecommBean(OttoConstants.COMMCOMM,getIntent().getStringExtra("itemId")));

                    }else if (tabType.equals("video")){
                        OttoBus.getInstance().post(new OVideoBean(OttoConstants.COMMCOMM,getIntent().getStringExtra("itemId")));

                    }else if (tabType.equals("picture")){
                        OttoBus.getInstance().post(new OPictureBean(OttoConstants.COMMCOMM,getIntent().getStringExtra("itemId")));
                    }

                    EventBus.getDefault().post(new MyCommunityLikeReply(0,1,getIntent().getStringExtra("itemId"),""));
                }

            }
        });
    }

    private void getIntentData(){
        VIDEO_TYPE=getIntent().getStringExtra("itemType");
        SharePreferenceUtil.getInstance(VideoDetailsActivity.this).setString(SharedPerfenceConstant.VIDEOSTATUS,VIDEO_TYPE);

//        cDetailsListBean = (CDetailsListBean) getIntent().getSerializableExtra("bean");
        if (VIDEO_TYPE.equals(VIDEO_VERTICAL)){
            setAllControlsVisiblity(View.VISIBLE,View.VISIBLE,View.GONE,View.GONE);
        }else if (VIDEO_TYPE.equals(VIDEO_HORIZONTAL)){
            setAllControlsVisiblity(View.VISIBLE,View.GONE,View.VISIBLE,View.GONE);
        }else if (VIDEO_TYPE.equals(VIDEO_PICTURE)){
            setAllControlsVisiblity(View.GONE,View.GONE,View.VISIBLE,View.VISIBLE);
            ll_tabbar.setVisibility(View.VISIBLE);
            include_head.setVisibility(View.GONE);
        }
    }


    /**
     * 底部view
     */
    private void bottomVisibility(){
        scrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            @Override
//            public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
            public void onScrollChange(NestedScrollView view, int i, int position, int i2, int under) {
                if (VIDEO_TYPE.equals(VIDEO_VERTICAL)){
                    if (v==0){
                        v = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 51, getResources().getDisplayMetrics());
                    }
                    if (position >= v){
                        replyBarBaseBottom.setY(0);
                        replyBarBaseBottom.setBackground(false);
                    }else if (position == 0){
                        replyBarBaseBottom.setY(0);
                        replyBarBaseBottom.setBackground(true);
                    }else{
                        replyBarBaseBottom.setY(v-position);
                        replyBarBaseBottom.setBackground(false);
                    }


//                    if (position>=100){
//                        setAllControlsVisiblity(View.VISIBLE,View.GONE,View.VISIBLE,View.GONE);
//                    }else if (under>position && position<100){
//                        setAllControlsVisiblity(View.VISIBLE,View.VISIBLE,View.GONE,View.GONE);
//                    }
                    if (position>=videoHeight){
                        mHeaderLayout.setBackgroundColor(ContextCompat.getColor(VideoDetailsActivity.this, R.color.white));
                        mShowDraw.setImageResource(R.drawable.icon_back);
                        mView.setVisibility(View.VISIBLE);
//                        QmzbVideoPlayer.onChildViewDetachedFromWindow(qmzbMediaView);
                        iv_more.setImageResource(R.drawable.icon_community_more_black);
                    }else if (under>position && position<videoHeight){
                        mHeaderLayout.setBackgroundColor(ContextCompat.getColor(VideoDetailsActivity.this, R.color.clear));
                        mShowDraw.setImageResource(R.drawable.icon_back_white);
                        mView.setVisibility(View.GONE);
//                        QmzbVideoPlayer.onChildViewAttachedToWindow(qmzbMediaView, R.id.cdetails_mediaview);
                        iv_more.setImageResource(R.drawable.icon_community_more_white);
                    }
                }else if (VIDEO_TYPE.equals(VIDEO_HORIZONTAL)){
                    if (position>=500){

                        mHeaderLayout.setBackgroundColor(ContextCompat.getColor(VideoDetailsActivity.this, R.color.white));
                        mShowDraw.setImageResource(R.drawable.icon_back);
                        mView.setVisibility(View.VISIBLE);
                        Log.e("播放器状态"+VIDEO_TYPE);
//                        QmzbVideoPlayer.onChildViewDetachedFromWindow(qmzbMediaView);
                        iv_more.setImageResource(R.drawable.icon_community_more_black);

                    }else if (under>position && position<500){

                        mHeaderLayout.setBackgroundColor(ContextCompat.getColor(VideoDetailsActivity.this, R.color.clear));
                        mShowDraw.setImageResource(R.drawable.icon_back_white);
                        mView.setVisibility(View.GONE);
//                        QmzbVideoPlayer.onChildViewAttachedToWindow(qmzbMediaView, R.id.cdetails_mediaview);
                        iv_more.setImageResource(R.drawable.icon_community_more_white);
                    }
                }else if (VIDEO_TYPE.equals(VIDEO_PICTURE)){

                }
            }
        });
//        scrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
//            @Override
//            public void onScrollChange(View view, int i, int position, int i2, int under) {
//
//
//
//                //视频是否可见
////                videoVisibility();
//            }
//        });
    }

    /**
     *  图文的加载
     */
    private void pictureData(){
        if (cDetailsInfoBean.getPics() !=null){
//            final List<String> array = new ArrayList<>();
//            final List<String> gif_array=new ArrayList<>();
//
//            for (int i=0;i<cDetailsInfoBean.getPics().size();i++){
//                array.add(cDetailsInfoBean.getPics().get(i).getU());
//                gif_array.add(cDetailsInfoBean.getPics().get(i).isIs_gif()? "1":"0");
//            }
//
//            String[] array1 = array.toArray(new String[array.size()]);

            ArrayList<ImageInfo> imageInfo = new ArrayList<>();
            for (int i = 0; i < cDetailsInfoBean.getPics().size(); i++) {
                ImageInfo info = new ImageInfo();
                info.setThumbnailUrl(cDetailsInfoBean.getPics().get(i).getU());
                info.setBigImageUrl(cDetailsInfoBean.getPics().get(i).getU());
                imageInfo.add(info);
            }
//            playskinScrollGirdView.setSingleImageSize(400);
            playskinScrollGirdView.setAdapter(new NineGridViewClickAdapter(this, imageInfo));

//            if (array1.length > 0) {
//                playskinScrollGirdView.setVisibility(View.VISIBLE);
//                playskinScrollGirdView.setAdapter(new PlayskinGirdAdapter(array1, this,gif_array));
//                playskinScrollGirdView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//                    @Override
//                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                        //点击放大浏览
//                        CommDetailsActivity.startCommDetailsActivity(VideoDetailsActivity.this,array,position);
//                    }
//                });
//            } else {
//                playskinScrollGirdView.setVisibility(View.GONE);
//            }
        }
    }



    public void setAllControlsVisiblity(int thumvideo,int thumbImg,int thumbtab,int thumbpicture) {
        qmzbMediaView.setVisibility(thumvideo);
//        replyBarBase.setVisibility(thumbImg);
        v = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 51, getResources().getDisplayMetrics());
        if (thumbtab == View.GONE){
            replyBarBaseBottom.setY(0);
            replyBarBaseBottom.setBackground(true);
        }
//        replyBarBaseBottom.setVisibility(thumbtab);
//        playskinScrollGirdView.setVisibility(thumbpicture);
    }


    private void initData(boolean isRefresh){
//        int size =mData.size();
//        if (mData!=null){
//            size = mData.size();
//        }
//        if (size % 10 == 0) {
//            page = (size / 10) + 1;
//        } else {
//            page = (size / 10) + 2;
//        }

        if (isRefresh){
            page = 1;
        }else {
            page++;
        }

        MapComm mapComm=new MapComm();
        mapComm.put("page", String.valueOf(page));
        mapComm.put("pagesize","10");
        mapComm.put("post_id",itemId);
        getPresenter().getVDetailsList(MapComm.getMap());
    }


    /**
     * 播放视频
     */
    private void playVideo() {

        if (! VIDEO_TYPE.equals(VIDEO_PICTURE)){
            if (cDetailsInfoBean != null && cDetailsInfoBean.getVideo() != null) {
                if (cDetailsInfoBean.getVideo().getU() != null)
                    qmzbMediaView.prepareVideo(cDetailsInfoBean.getVideo().getU());
            }
        }else{
            //图文
            pictureData();
        }

        setReplyBar(cDetailsInfoBean);

        UIUtils.loadImage(mUserIcon,cDetailsInfoBean.getUser().getAvator());

        mUserIcon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(VideoDetailsActivity.this, LookUserCenterActivity.class);
                intent.putExtra("uid",cDetailsInfoBean.getUser().getUid());
                intent.putExtra("type","video");
                startActivity(intent);
            }
        });

        mNickName.setText(cDetailsInfoBean.getUser().getNickname());

        mNickName.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(VideoDetailsActivity.this, LookUserCenterActivity.class);
                intent.putExtra("uid",cDetailsInfoBean.getUser().getUid());
                intent.putExtra("type","video");
                startActivity(intent);
            }
        });

        String content;

        topicContent="";

        if (cDetailsInfoBean.getTopic().size()>0)
            for (int i=0;i<cDetailsInfoBean.getTopic().size();i++){
                topicContent="#"+cDetailsInfoBean.getTopic().get(i).getTitle()+"#";
                cDetailsInfoBean.setContent(topicContent+cDetailsInfoBean.getContent());
            }

        content=cDetailsInfoBean.getContent();
        if (!TextUtils.isEmpty(content)){
            mContentView.setText(setTextView(content, mContentView));
            mContentView.setVisibility(View.VISIBLE);
        }else {
            mContentView.setVisibility(View.GONE);
        }

        String priaiseComm = cDetailsInfoBean.getComment_num();// FormUnitUtils.form(BigDecimal.valueOf(Long.parseLong(cDetailsInfoBean.getComment_num())), "w");
        if (TextUtils.equals("0",priaiseComm)){
            priaiseComm = "评论";
        }
        mCommentsCount.setText(priaiseComm);

        String priaiseShare = cDetailsInfoBean.getShare_num();// FormUnitUtils.form(BigDecimal.valueOf(cDetailsInfoBean.getShare_num()), "w");
        if (TextUtils.equals("0",priaiseShare)){
            priaiseShare = "分享";
        }
        mShareCount.setText(priaiseShare);

        isLike();

    }

    /**
     * 帖子的点赞状态
     */
    public void isLike(){

        Drawable nav_up;
        if (cDetailsInfoBean.getIs_like()==1){
            nav_up = getResources().getDrawable(R.drawable.icon_community_zan_true);
            nav_up.setBounds(0, 0, nav_up.getMinimumWidth(), nav_up.getMinimumHeight());
            mCommLikeCount.setCompoundDrawables(nav_up, null, null, null);

        }else if (cDetailsInfoBean.getIs_like()==0){
            nav_up =getResources().getDrawable(R.drawable.icon_community_zan_false);
            nav_up.setBounds(0, 0, nav_up.getMinimumWidth(), nav_up.getMinimumHeight());
            mCommLikeCount.setCompoundDrawables(nav_up, null, null, null);
        }

        String priaise =cDetailsInfoBean.getLike_num();// FormUnitUtils.form(BigDecimal.valueOf(cDetailsInfoBean.getLike_num()), "w");
        if (TextUtils.equals("0",priaise)){
            priaise = "点赞";
        }
        mCommLikeCount.setText(priaise);

    }

    private CharSequence setTextView(String desc, TextView tv) {

        /*正则表达式  取出 两个#之间的内容 （不包含#） */
        Pattern p = Pattern.compile("#([^\\#|]+)#");
        /*android 提供的 具有强大的CharSequence 处理能力 各种区域处理*/
        SpannableString ss = new SpannableString(desc);
        Matcher m = p.matcher(desc);
        /*由于@昵称、#话题#、http://等这些关键字是可以点击的，所以我们需要对TextView做一些处理，需要去设置它的MovementMethod*/
        if (m.find()) {
            // 要实现文字的点击效果，这里需要做特殊处理
            tv.setMovementMethod(LinkMovementMethod.getInstance());
            // 重置正则位置
            m.reset();
        }
        /*循环找出每个复合正则的字符串，逐个处理*/
        while (m.find()) {
            /*取出 字符串 前后添加#*/
            final String s = "#" + m.group(1) + "#";
            int startIndex = m.start(1) - 1;
            int endIndex = startIndex + s.length();
            /*区域处理*/
            ss.setSpan(new ForegroundColorSpan(Color.BLUE),startIndex,endIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            ss.setSpan(new ClickableSpan() {
                @Override
                public void onClick(View widget) {
                    //去掉两边的#号，获取点击的话题内容
                    String content=s.substring(1,s.length()-1);
                    String topicId="";//话题的id
                    for (int i=0;i<cDetailsInfoBean.getTopic().size();i++){
                        if (content.equals(cDetailsInfoBean.getTopic().get(i).getTitle())){
                            topicId=cDetailsInfoBean.getTopic().get(i).getId();
                        }
                    }
                    if (topicId.equals(itemId)){
                        return;
                    }
                    CommTopicActivity.startCommTopicActivity(VideoDetailsActivity.this,topicId);

                }
                @Override
                public void updateDrawState(TextPaint ds) {
                    //        super.updateDrawState(ds);
                    //    按自己需求    重写 父类方法.
                    //        字体变色
                    ds.setColor(Color.parseColor("#507daf"));
                    //            设置下划线
                    ds.setUnderlineText(false);
                }
            }, startIndex, endIndex, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }


        return ss;
    }

    @OnClick({R.id.showdraw,R.id.recomm_details_like,R.id.recomm_details_comments,R.id.recomm_details_share,R.id.ll_back})
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.showdraw:
                finish();
                break;
            case R.id.recomm_details_like:
                if (! SPUtils.isLogined()) {
                    LoginRegistActivity.startLoginRegistActivity(this);
                    return;
                }
                setLikeData();
                break;
            case R.id.recomm_details_comments:
                replyBar.showReplyBar(true,true);
                break;
            case R.id.ll_header_right:
            case R.id.iv_more:
            case R.id.recomm_details_share:
                Map<String,String> map=new HashMap<>();
                if (cDetailsInfoBean.getShare()==null){
                    return;
                }
                map.put("title",cDetailsInfoBean.getShare().getTitle());
                map.put("msc",cDetailsInfoBean.getShare().getDesc());
                map.put("url",cDetailsInfoBean.getShare().getH5_url());
                map.put("img",cDetailsInfoBean.getShare().getPic_url());
                map.put("type","1");
                map.put("id",cDetailsInfoBean.getId());
                CommunityShare.getInstance(map).show(getSupportFragmentManager().beginTransaction()
                        .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE),"ads");

                break;
            case R.id.ll_back:
                finish();
                break;
        }
    }

    @Override
    public VDetailsContract.Presenter getPresenter() {
        if (mPresenter==null){
            mPresenter=new VDetailsPresenter(this,this);
        }
        return mPresenter;
    }

    @Override
    public void setPresenter(VDetailsContract.Presenter presenter) {

    }

    @Override
    public void onVDetailsList(CDetailsBean list) {
        List<CDetailsListBean> list1 = list.getList();

        if (list1 != null && list1.size()>0){

        }else{
            smartRefreshLayout.setNoMoreData(true);
        }
        smartRefreshLayout.finishLoadMore(true);
//        mRecyclerView.setIsHaveData(false);
        mData.addAll(list.getList());
//        cDetailsInfoBean=list.getPost_info();//todo
        commDetailsAdapter.addData(list.getList());
        //如果是消息点击过来的，添加头部消息

        fromMSG();

        isScroll();
//        playMedia();
    }

    private void isScroll(){
        if (!TextUtils.isEmpty(isScroll)){
            if (TextUtils.equals("1",isScroll)){

                if (VIDEO_TYPE.equals(VIDEO_VERTICAL)){
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {

                            scrollView.scrollTo(0,getResources().getDisplayMetrics().heightPixels);
                        }
                    },200);
                }else if (VIDEO_TYPE.equals(VIDEO_HORIZONTAL)){
                    new Handler().postDelayed(new Runnable() {
                          @Override
                          public void run() {
                            int h = getResources().getDisplayMetrics().widthPixels * 9 /16;
                            scrollView.scrollTo(0,h);
                          }
                    },200);
                }else if (VIDEO_TYPE.equals(VIDEO_PICTURE)){
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {

                            int height = ll_xm.getHeight();
                            if (height != 0){
                                scrollView.smoothScrollTo(0,height);
                            }
                        }
                    },200);

                }

            }

            isScroll = "";
        }
    }

    /**
     * * 消息类型：0评论我的帖子
     * 1评论我的评论
     * 2在我的帖子中回复了别人
     * 3赞了我的帖子
     * 4赞了我的评论
     * 5其它
     * 6系统可点击消息
     * 7对我的音频点赞
     */
    private void fromMSG(){
        if (item != null && !isDEL){
//数据
            String id = item.get("id");//消息id
            final String uid = item.get("uid");//接收者UID
            String content = item.get("content");//消息内容

            final String type = item.get("type");//消息类型：0评论我的帖子1评论我的评论2在我的帖子中回复了别人3赞了我的帖子4赞了我的评论5其它6系统可点击消息7对我的音频点赞
            String jump_page = item.get("jump_page");//消息跳转页面：1帖子2评论3发布的音频
            String pic = item.get("pic");//对应的图片，空为无图片，否则为图片地址
            String related_id = item.get("related_id");//跳转到对应的id
            String send_uid = item.get("send_uid");//发送者的uid
            String add_time = item.get("add_time");//添加时间戳
            String read_time = item.get("read_time");//读取时间
            String update_time = item.get("update_time");//更新时间
            String author = item.get("author");//发送者的用户信息
            final String datetime = item.get("datetime");//发送时间，前端显示用
            String a_uid = "";
            String a_nickname = "";
            String a_avator = "";
            String a_sex = "";
            String a_sign = "";
            //对我评论的人的信息
            if (!TextUtils.isEmpty(author)) {
                ArrayList<Map<String, String>> authors = JSONUtils.getListMapByJson(author);
                if (authors.size() > 0) {
                    Map<String, String> map = authors.get(0);
                    a_uid = map.get("uid");
                    a_nickname = map.get("nickname");
                    a_avator = map.get("avator");
                    a_sex = map.get("sex");
                    a_sign = map.get("sign");
                }
            }
            //帖子的评论
            final String comment_res = item.get("comment_res");
            String comment_res_id = "";
            String coment_res_pics = "";
            String coment_res_content = "";
            String coment_res_post_id = "";
            if (!TextUtils.isEmpty(comment_res)){
                ArrayList<Map<String, String>> comment_res_list = JSONUtils.getListMapByJson(comment_res);
                if (comment_res_list.size()>0){
                    Map<String, String> map = comment_res_list.get(0);
                    comment_res_id = map.get("id");
                    coment_res_pics = map.get("pics");
                    coment_res_content = map.get("content");
                    coment_res_post_id = map.get("post_id");
                }
            }
            //别人回复你的信息
            final String reply_res = item.get("reply_res");
            String reply_res_content="";//别人回复我的信息
            String reply_res_id = "";//回复的回复的id
            if (!TextUtils.isEmpty(reply_res)){
                ArrayList<Map<String, String>> reply_ress = JSONUtils.getListMapByJson(reply_res);
                if (reply_ress.size()>0){
                    Map<String, String> map = reply_ress.get(0);
                    reply_res_id = map.get("id");
                    reply_res_content = map.get("content");
                    String status = map.get("status");
                }
            }
            //当前帖子的信息，展示右侧的图片或者文字
            String post_res = item.get("post_res");
            String post_res_content = "";//右侧文字 没有图片就展示文字
            String pic_right = "";//右侧图片
            String post_res_id = "";//帖子的id
            String post_res_category = "";
            String videoW = "";
            String videoH = "";
            if (!TextUtils.isEmpty(post_res)){
                ArrayList<Map<String, String>> post_res_list = JSONUtils.getListMapByJson(post_res);
                if (post_res_list.size()>0){
                    Map<String, String> map = post_res_list.get(0);
                    post_res_id = map.get("id");
                    post_res_content = map.get("content");
                    post_res_category = map.get("category");//1 图文 2 视频
                    if (TextUtils.equals("1",post_res_category)){
                        String post_res_pics = map.get("pics");
                        ArrayList<Map<String, String>> pics = JSONUtils.getListMapByJson(post_res_pics);
                        if (pics.size()>0){
                            Map<String, String> map1 = pics.get(0);
                            pic_right = map1.get("");
                        }
                    }else{
                        String post_res_video = map.get("video");
                        ArrayList<Map<String, String>> videos = JSONUtils.getListMapByJson(post_res_video);
                        if (videos.size()>0){
                            Map<String, String> map2 = videos.get(0);
                            videoW = map2.get("w");
                            videoH = map2.get("h");
                            String cover_img = map2.get("cover_img");
                            ArrayList<Map<String, String>> cover_imgs = JSONUtils.getListMapByJson(cover_img);
                            if (cover_imgs.size()>0){
                                Map<String, String> map1 = cover_imgs.get(0);
                                pic_right = map1.get("u");
                            }
                        }
                    }
                }
            }


            /**
             * * 消息类型：0评论我的帖子
             * 1评论我的评论
             * 2在我的帖子中回复了别人
             * 3赞了我的帖子
             * 4赞了我的评论
             * 5其它
             * 6系统可点击消息
             * 7对我的音频点赞
             */
            if (type.equals("0") || type.equals("4")){
                CDetailsListBean msgReplyListBean = new CDetailsListBean();
                msgReplyListBean.setId(comment_res_id);
                msgReplyListBean.setPost_id(coment_res_post_id);
                msgReplyListBean.setContent(coment_res_content);
                msgReplyListBean.setLike_num("0");
                msgReplyListBean.setIs_like(0);
                msgReplyListBean.setReply_num("0");
                msgReplyListBean.setDate(datetime);
                UserBean userBeanX = new UserBean();
                userBeanX.setSex(a_sex);
                userBeanX.setAvator(a_avator);
                userBeanX.setNickname(a_nickname);
                userBeanX.setUid(a_uid);
                msgReplyListBean.setUser(userBeanX);

                List<RecommPictureBean> picsBeans = new ArrayList<>();
                if (!TextUtils.isEmpty(coment_res_pics)) {
                    ArrayList<Map<String, String>> picss = JSONUtils.getListMapByJson(coment_res_pics);
                    for (int i = 0; i < picss.size(); i++) {
                        Map<String, String> o = picss.get(i);
                        String w = o.get("w");
                        String h = o.get("h");
                        String u = o.get("u");
                        boolean is_gif = Boolean.valueOf(o.get("is_gif"));

                        RecommPictureBean picsBean = new RecommPictureBean();
                        picsBean.setW(w);
                        picsBean.setH(h);
                        picsBean.setU(u);
                        picsBean.setIs_gif(is_gif);
                        picsBeans.add(picsBean);
                    }
                }

                msgReplyListBean.setPics(picsBeans);

                if (msgReplyListBean !=null){
                    if (commDetailsAdapter.getData().size()>0){

                        CDetailsListBean cDetailsListBeana = commDetailsAdapter.getData().get(0);
                        if (!TextUtils.equals(msgReplyListBean.getId(),cDetailsListBeana.getId())){
                            for (int i=0;i<commDetailsAdapter.getData().size();i++){
                                CDetailsListBean cDetailsListBeanm = commDetailsAdapter.getData().get(i);
                                if (TextUtils.equals(msgReplyListBean.getId(),cDetailsListBeanm.getId())){
                                    commDetailsAdapter.getData().remove(i);
                                    break;
                                }
                            }
                            commDetailsAdapter.addItem( msgReplyListBean);
                        }
                    }

                    if (VIDEO_TYPE.equals(VIDEO_VERTICAL)){
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {

                                scrollView.scrollTo(0,getResources().getDisplayMetrics().heightPixels);
                            }
                        },200);
                    }else if (VIDEO_TYPE.equals(VIDEO_HORIZONTAL)){
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                int h = getResources().getDisplayMetrics().widthPixels * 9 /16;
                                scrollView.scrollTo(0,h);
                            }
                        },200);
                    }else if (VIDEO_TYPE.equals(VIDEO_PICTURE)){
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {

                                int height = ll_xm.getHeight();
                                if (height != 0){
                                    scrollView.smoothScrollTo(0,height);
                                }
                            }
                        },200);

                    }
                }
            }else if (type.equals("1")) {
                Intent intent = new Intent(this, CommentDetailAcitivity.class);
                intent.putExtra("post_id", post_res_id);
                intent.putExtra("reply_id", comment_res_id);
                intent.putExtra("uid", uid);
                intent.putExtra("type", type);
                intent.putExtra("msg", (Serializable) item);
                startActivity(intent);

            }else if (type.equals("3")){

            }

            item = null;
        }


    }

    @Override
    public void onLikeList(String list) {
        if (list.toString().equals("成功")){
            if (isLikeType==0){

                isLike=isLike==0 ? 1 : 0;

                int count= isLike==0 ? -1 : 1;

                cDetailsInfoBean.setIs_like(isLike);

                String like_num = cDetailsInfoBean.getLike_num();
                if (!like_num.contains("w") && !like_num.contains("k")){
                    like_num = (Long.valueOf(like_num) + count) + "";
                    cDetailsInfoBean.setLike_num(like_num);
                }
                mSharePreferenceUtil.setInt(SharedPerfenceConstant.DEATILSLIKECLICK,cDetailsInfoBean.getIs_like());

                //这里用来区分是哪一个tab点击的，来进行不同的观察者接受事件
                String tabType=getIntent().getStringExtra("tabType");

                if (tabType.equals("recomm")){
                    OttoBus.getInstance().post(new ORecommBean(OttoConstants.COMMCLICK,getIntent().getStringExtra("itemId")));

                }else if (tabType.equals("video")){
                    OttoBus.getInstance().post(new OVideoBean(OttoConstants.COMMCLICK,getIntent().getStringExtra("itemId")));

                }else if (tabType.equals("picture")){
                    OttoBus.getInstance().post(new OPictureBean(OttoConstants.COMMCLICK,getIntent().getStringExtra("itemId")));
                }

                EventBus.getDefault().post(new MyCommunityLikeReply(0,0,itemId,""));

                Log.e(" 获取详情页的点赞的状态"+cDetailsInfoBean.getIs_like());
                isLike();
            }else{
                isLikeList=isLikeList==0 ? 1 : 0;

                int count= isLikeList==0 ? - 1 : 1;

                mData.get(likePosition).setIs_like(isLikeList);
                String like_num = commDetailsAdapter.commBeans.get(likePosition).getLike_num();
                if (!like_num.contains("w") && !like_num.contains("k")){
                    like_num = (Long.valueOf(like_num) + count) + "";
                    commDetailsAdapter.commBeans.get(likePosition).setLike_num(like_num);
                }
//                commDetailsAdapter.commBeans.get(likePosition).setLike_num(commDetailsAdapter.commBeans.get(likePosition).getLike_num()+count);

                commDetailsAdapter.commBeans.get(likePosition).setIs_like(isLikeList);

                commDetailsAdapter.isLike(likePosition);
                //判断是否点击的神评
                if (mData.get(likePosition).getIs_god().equals("1")){
                    mSharePreferenceUtil.setInt(SharedPerfenceConstant.DEATILSLIKECLICK,isLikeList);

                    //这里用来区分是哪一个tab点击的，来进行不同的观察者接受事件
                    String tabType=getIntent().getStringExtra("tabType");

                    if (tabType.equals("recomm")){
                        OttoBus.getInstance().post(new ORecommBean(OttoConstants.COMMGODCLICK,getIntent().getStringExtra("itemId")));

                    }else if (tabType.equals("video")){
                        OttoBus.getInstance().post(new OVideoBean(OttoConstants.COMMGODCLICK,getIntent().getStringExtra("itemId")));

                    }else if (tabType.equals("picture")){
                        OttoBus.getInstance().post(new OPictureBean(OttoConstants.COMMGODCLICK,getIntent().getStringExtra("itemId")));
                    }
                }

            }
        }
    }

    private void playMedia(){
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                Message message=new Message();
                message.what=0;
                playHandler.handleMessage(message);
            }
        },200);
    }

    @Override
    public void onLoad() {
        Log.e("dasdas");
//        initData(false);
//        RecyclerViewStateUtils.setFooterViewState(this, mRecyclerView, 20, LoadingFooter.State.Loading, null);
    }

    @Override
    public void loadFinish() {
//        mRecyclerView.setIsHaveData(true);
//        RecyclerViewStateUtils.setFooterViewState(this, mRecyclerView, 20, LoadingFooter.State.TheEnd, null); //21

    }

    @Override
    public void isLikeClick(int position) {
        isLikeType=1;
        likePosition=position;
        isLikeList=mData.get(position).getIs_like();
        int count= isLikeList==0 ? 1 : 2;

        MapComm mapComm=new MapComm();
        mapComm.put("id",mData.get(position).getId());
        mapComm.put("type","2");
        mapComm.put("status",String.valueOf(count));
        getPresenter().getLikeList(MapComm.getMap());

//        for (int i = 0; i < mRecyclerView.getChildCount(); i++) {
//            if (mRecyclerView.getChildAt(i) != null) {
//                RecyclerView.ViewHolder childViewHolder = mRecyclerView.getChildViewHolder(mRecyclerView.getChildAt(i));
//                if (childViewHolder instanceof CommDetailsAdapter.FocusPictureViewHolder) {
//                    focusNormalViewHolder= (CommDetailsAdapter.FocusNormalViewHolder) childViewHolder;
//                }
//                return;
//            }
//        }
    }

    @Override
    public void onRefresh() {

    }

    private class PlayHandler extends Handler{

        @Override
        public void handleMessage(Message msg){
            super.handleMessage(msg);
            switch (msg.what){
                case 0:
                    playVideo();
                    break;
            }
        }
    }

    private void setLikeData(){
        isLikeType=0;
        isLike=cDetailsInfoBean.getIs_like();
        int count= isLike==0 ? 1 : 2;

        MapComm mapComm=new MapComm();
        mapComm.put("id",cDetailsInfoBean.getId());
        mapComm.put("type","1");
        mapComm.put("status",String.valueOf(count));
        getPresenter().getLikeList(MapComm.getMap());
    }

    @Override
    public void onVDetailsFailure() {
        smartRefreshLayout.finishLoadMore(false);
    }

    @Override
    public void onVDetailsNoMore() {

    }

    @Override
    public void onNoNetWork() {

    }

    @Override
    public void onPause() {
        super.onPause();
        if (!VIDEO_TYPE.equals(VIDEO_PICTURE)) {
            qmzbMediaView.onPlayOnPause();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
//        if (!VIDEO_TYPE.equals(VIDEO_PICTURE))
////            playMedia();
//            QmzbVideoPlayer.onPlayOnResume();
        if (! VIDEO_TYPE.equals(VIDEO_PICTURE)){
            if (cDetailsInfoBean != null && cDetailsInfoBean.getVideo() != null) {
                if (cDetailsInfoBean.getVideo().getU() != null)

                    if (!QmzbVideoPlayer.isPause()) {
                        qmzbMediaView.startVideo();
//                        qmzbMediaView.onPlayOnResume();
//                        qmzbMediaView.prepareVideo(cDetailsInfoBean.getVideo().getU());
                    }
            }
        }


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        if (!VIDEO_TYPE.equals(VIDEO_PICTURE))
//        QmzbMediaManager.instance().releaseMediaPlayer();

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (replyBar != null){
            replyBar.onActivityResult(requestCode,resultCode,data);
        }
    }

    @Override
    public void onBackPressed() {
        if (QmzbVideoPlayer.backPress()) {
            return;
        }
        if (isTaskRoot()){
            finish();
            Intent intent = new Intent(this,MainActivity.class);
            startActivity(intent);
        }else {
            super.onBackPressed();
        }
    }

}
